package com.android.djlmapp.activity.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.android.djlmapp.R;
import com.android.djlmapp.tools.global.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileOutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class SaveCodeActivity extends Activity {


    @BindView(R.id.iv_save_code)
    ImageView ivSaveCode;
    private String codeurl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_save_code);
        ButterKnife.bind(this);
        initView();
    }

    protected void initView() {
        codeurl = getIntent().getStringExtra("CODEURL");
        if (!TextUtils.isEmpty(codeurl)) {
            ivSaveCode.setVisibility(View.VISIBLE);
            Glide.with(SaveCodeActivity.this).load(codeurl).into(ivSaveCode);
        } else {
            ivSaveCode.setVisibility(View.GONE);
            ToastUtils.showShortToast(SaveCodeActivity.this, "二维码图片获取失败");
        }
        ivSaveCode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                SaveCodeActivityPermissionsDispatcher.onNeedPermissionWriteReadWithCheck(SaveCodeActivity.this);
                return false;
            }
        });
    }


    private void downImg() {
        Glide.with(SaveCodeActivity.this).asBitmap().load(codeurl).listener(new RequestListener<Bitmap>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                ToastUtils.showShortToast(SaveCodeActivity.this, "保存失败，请检查网络");
                return false;
            }

            @Override
            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                saveImageToGallery(resource);
                return false;
            }
        }).submit();
    }

    /**
     * 保存图片
     *
     * @param bmp
     * @return
     */
    private void saveImageToGallery(Bitmap bmp) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download" + File.separator + "Djlm";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String fileName = "zcord.jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            ToastUtils.showShortToast(SaveCodeActivity.this, "图片已保存");
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShortToast(SaveCodeActivity.this, "保存失败");
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNeedPermissionWriteRead() {
        downImg();
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onDeniedWriteRead() {
        ToastUtils.showShortToast(SaveCodeActivity.this, "暂无权限");
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRational(final PermissionRequest request) {
        request.proceed();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SaveCodeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
